import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import Logger from './Logger';
import { Context } from '@kit.AbilityKit';
import { util } from '@kit.ArkTS';


/**
 * 警告模拟器不可以运行
 * */
export async function getJsonFromRawfile(context:Context,path:string){
  // const rawFile = await context.resourceManager.getRawFileContent(path)
  // let textDecoder = util.TextDecoder.create("utf-8",{ignoreBOM:true})
  // let retStr = textDecoder.decodeWithStream(rawFile,{stream:false})
  // return retStr;
  try {
    context.resourceManager.getRawFd(path, (error, value) => {
      if (error != null) {
        console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.${error.name}`);
      } else {
        let fd = value.fd;
        let offset = value.offset;
        let length = value.length;
        Logger.info("======>",fd.toLocaleString(),offset.toString(),length.toString())
      }
    });
  } catch (error) {
    console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`)
  };
}

export function createFile(context,content) {
  // 获取应用文件路径
  let filesDir = context.filesDir;

  // 新建并打开文件
  let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  // 写入一段内容至文件
  let writeLen = fs.writeSync(file.fd, content);
  console.info("The length of str is: " + writeLen);
  // 从文件读取一段内容
  let buf = new ArrayBuffer(1024);
  let readLen = fs.readSync(file.fd, buf, { offset: 0 });
  console.info("the content of file: " + String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
  // 关闭文件
  fs.closeSync(file);
}
export function readWriteFile(context:common.UIAbilityContext) {
  // 获取应用文件路径
  let filesDir = context.filesDir;
  // 打开文件
  let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE);
  let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  // 读取源文件内容并写入至目的文件
  let bufSize = 1028;
  let readSize = 0;
  let buf = new ArrayBuffer(bufSize);
  let readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
  while (readLen > 0) {
    readSize += readLen;
    fs.writeSync(destFile.fd, buf);
    readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
  }
  Logger.debug("读取文件长度：",readSize.toString())
  // 关闭文件
  try {
    fs.closeSync(srcFile);
    fs.closeSync(destFile);
  }catch (err){
    Logger.error(err)
  }
}